package com.bnzj.cloud.business.core.web;

import com.bnzj.cloud.business.core.service.SysDepartmentService;
import com.bnzj.cloud.business.core.persistence.entity.SysDepartment;
import com.bnzj.core.action.ActionType;
import com.bnzj.core.action.annotation.Action;
import com.bnzj.core.exception.BusinessException;
import com.bnzj.core.persistence.query.CompareExpression;
import com.bnzj.core.persistence.query.CompareType;
import com.bnzj.core.persistence.query.IExpression;
import com.bnzj.core.persistence.query.QueryHelpBean;
import com.bnzj.core.persistence.util.EntityUtils;
import com.bnzj.core.rest.CurrentUserService;
import com.bnzj.core.rest.ResponseResult;
import com.bnzj.core.rest.ResultCode;
import com.bnzj.core.rest.UserInfo;
import com.bnzj.core.util.BeanUtils;
import com.bnzj.core.webmvc.util.WebMvcUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * @author Barry
 * @createDate 2020/2/17
 * @description
 */
@Tag(name = "部门", description = "部门管理：部门的CURD等")
@RestController
@RequestMapping("/system/department")
public class SysDepartmentController {

    @Autowired
    private CurrentUserService gatewayCurrentUserService;

    @Autowired
    private SysDepartmentService sysDepartmentService;

    @Operation(summary = "分页查询", description = "",
            parameters = {
                    @Parameter(name = "keyWord", description = "keyWord关键子查询根据部门名称/编号/部门全称，模糊搜索", allowEmptyValue = true, allowReserved = true, schema = @Schema(implementation = String.class, description = "无"))
                    , @Parameter(name = "enabled", description = "enabled 禁用0启用1 默认查已启用", allowEmptyValue = true, allowReserved = true, schema = @Schema(implementation = String.class, description = "无"))
            })
    @GetMapping(value = "/page")
    public ResponseResult<Page<SysDepartment>> getDepartmentPage(HttpServletRequest request, @RequestParam(value = "enabled", required = false) Boolean enabled) {
        Pageable pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.DESC, "create_time"));
        QueryHelpBean queryHelpBean = SysDepartmentService.getQueryHelpBean();
        queryHelpBean.setPageable(pageable);
        IExpression andCondition1 = CompareExpression.build("d.enabled", CompareType.equal, enabled);
        //默认查已经启用
        //根据部门名称/编号/部门全称，模糊搜索
        IExpression orCondition1 = CompareExpression.build("d.name", CompareType.like, request.getParameter("keyWord"));
        IExpression orCondition2 = CompareExpression.build("d.code", CompareType.like, request.getParameter("keyWord"));
        IExpression orCondition3 = CompareExpression.build("d.module_name", CompareType.like, request.getParameter("keyWord"));
        IExpression orCondition4 = CompareExpression.build("d.v_full_name", CompareType.like, request.getParameter("keyWord"));
        queryHelpBean.addWhere(andCondition1.or(orCondition1, orCondition2, orCondition3, orCondition4));
        Page<SysDepartment> all = sysDepartmentService.findAll(queryHelpBean);
        return ResponseResult.success(all);
    }


    @Operation(summary = "根据id查询")
    @GetMapping("/one/{id}")
    public ResponseResult<SysDepartment> getById(@Parameter(in = ParameterIn.PATH, name = "id", description = "主键", required = true) @PathVariable("id") Long id) {
        Optional<SysDepartment> optional = sysDepartmentService.findById(id);
        return ResponseResult.success(optional.orElse(null));
    }

    @Action(descriprion = "部门保存", moduleName = "部门", operateType = ActionType.ADD_DATA)
    @Operation(summary = "保存")
    @PostMapping("/save")
    public ResponseResult<?> addDepartment(@RequestBody SysDepartment sysDepartment) {
        UserInfo userInfo = gatewayCurrentUserService.getUserInfo();
        EntityUtils.saveBefore(sysDepartment, userInfo.getAccount(), userInfo.getName());
        sysDepartmentService.save(sysDepartment);
        return ResponseResult.success();
    }

    @Action(descriprion = "部门更新", moduleName = "部门", operateType = ActionType.UPDATE_DATA)
    @Operation(summary = "更新")
    @PostMapping("/update")
    public ResponseResult<?> updateDepartment(@RequestBody SysDepartment sysDepartment) {
        if (ObjectUtils.isEmpty(sysDepartment.getId())) {
            ResultCode resultCode = ResultCode.getResultCode(ResultCode.BAD_REQUEST);
            throw new BusinessException(resultCode.getMsg(), "" + resultCode.getCode());
        }
        UserInfo userInfo = gatewayCurrentUserService.getUserInfo();
        EntityUtils.saveBefore(sysDepartment, userInfo.getAccount(), userInfo.getName());
        Optional<SysDepartment> sysDepartmentOpt = sysDepartmentService.findById(sysDepartment.getId());
        if (!sysDepartmentOpt.isPresent()) {
            ResultCode resultCode = ResultCode.getResultCode(ResultCode.RESOURCE_NOT_EXIST);
            throw new BusinessException(resultCode.getMsg(), "" + resultCode.getCode());
        }
        SysDepartment sysDepartmentDb = sysDepartmentOpt.get();
        BeanUtils.copyProperties(sysDepartment, sysDepartmentDb);
        sysDepartmentService.save(sysDepartmentDb);
        return ResponseResult.success();
    }

    @Operation(summary = "禁用", description = "根据部门id集合禁用部门")
    @Action(descriprion = "部门禁用", moduleName = "部门", operateType = ActionType.UPDATE_DATA)
    @PostMapping("/disable")
    public void disable(@RequestBody List<Long> ids) {
        sysDepartmentService.disable(ids);
    }


    @Operation(summary = "获取所有启用部门", description = "获取所有已启用部门")
    @GetMapping("/all/enabled")
    public ResponseResult<Set<Long>> findAllIdByEnabled() {
        Set<Long> allEnabled = sysDepartmentService.findAllIdByEnabled();
        return ResponseResult.success(allEnabled);
    }

}
